package com.shqcjd.preinstallmobile.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.shqcjd.preinstallmobile.R;
import com.shqcjd.preinstallmobile.api.ApiService;
import com.shqcjd.preinstallmobile.app.MyApp;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallmobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallmobile.model.ResponseData;
import com.shqcjd.preinstallmobile.model.pojo.PointInfoBean;
import com.shqcjd.preinstallmobile.model.pojo.TrackInfoBean;
import com.shqcjd.preinstallmobile.ui.adapter.TrackInfoAdapter;
import com.shqcjd.preinstallmobile.ui.base.BaseActivity;
import com.shqcjd.preinstallmobile.ui.base.BasePresenter;
import com.shqcjd.preinstallmobile.util.ToastUtils;
import com.shqcjd.preinstallmobile.util.UIUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 轨迹详情页
 */
public class NtrackDetailsActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener  {


    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.mv_route)
    MapView mvRoute;
    @BindView(R.id.rv_ntrack_details)
    RecyclerView rvNtrackDetails;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;
    private TrackInfoAdapter trackInfoAdapter;
    private int taskId, routeId;
    private View notDataView;
    private Context context;

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_ntrack_details;
    }

    @Override
    public void init() {
        super.init();
        context = this;
        taskId = getIntent().getIntExtra("taskId", -1);
        routeId = getIntent().getIntExtra("routeId", -1);
//        taskId = 127;
//        routeId = 81;
    }

    @Override
    public void initView() {
        super.initView();
        tvIncludeTitle.setText("轨迹详情");
        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

            }
        });
        notDataView = getLayoutInflater().inflate(R.layout.layout_no_data, (ViewGroup) swipeRefresh.getParent(), false);
        initAdapter();
    }

    @Override
    public void initData() {
        RxPermissions permissions = new RxPermissions(NtrackDetailsActivity.this);
        permissions.setLogging(true);
        permissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {

                        } else {
                            ToastUtils.show(NtrackDetailsActivity.this, "需要获取定位的权限", Toast.LENGTH_SHORT);
                        }
                    }
                });
        refresh();
    }


    private void initAdapter() {
        swipeRefresh.setOnRefreshListener(this);
        trackInfoAdapter = new TrackInfoAdapter();
        rvNtrackDetails.setLayoutManager(new LinearLayoutManager(this));
        rvNtrackDetails.setAdapter(trackInfoAdapter);
        trackInfoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    TrackInfoBean.EquipmentsBean mBean = (TrackInfoBean.EquipmentsBean) adapter.getData().get(position);
                    Intent it = new Intent(context, EquipmentInspectionRecordActivity.class);
                    it.putExtra("kks", mBean.kks);
                    it.putExtra("tId", taskId);
                    startActivity(it);
            }
        });
    }

    private void refresh() {
        ApiService.getTrackInfo(taskId, routeId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<TrackInfoBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showRefreshView(true);
                    }

                    @Override
                    public void _onNext(ResponseData<TrackInfoBean> retData) {
                        if (retData.retCode == 10000) {
                            int size = retData.data.equipments.size();
                                                initMapView(retData.data.points);
                            if (size > 0) {
                                trackInfoAdapter.setNewData(retData.data.equipments);
                            } else {
                                trackInfoAdapter.setNewData(null);
                                trackInfoAdapter.setEmptyView(notDataView);
                            }
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        showRefreshView(false);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        showRefreshView(false);
                    }
                });
    }
    public void showRefreshView(Boolean refresh) {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(refresh);
            }
        });
    }


    @Override
    public void onRefresh() {
        refresh();
    }

    private void initMapView(List<TrackInfoBean.PointsBean> patrol_point) {
        MyApp.startLocation();
        MyApp.setOnLocationCallBack(new MyApp.OnLocationInterface() {
            @Override
            public void onLocationInterface(AMapLocation aMapLocation) {
                LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());//构造一个位置
                mvRoute.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
            }
        });

        List<LatLng> latLngs = new ArrayList<LatLng>();
        if(patrol_point.size()==0){
            return;
        }
        for (int i = 0; i <= patrol_point.size(); i++) {
            if (i == patrol_point.size()) {
                latLngs.add(UIUtils.getGpsChangeLocation(Double.parseDouble(patrol_point.get(0).latitude), Double.parseDouble(patrol_point.get(0).longitude), context));
            } else {
                latLngs.add(UIUtils.getGpsChangeLocation(Double.parseDouble(patrol_point.get(i).latitude), Double.parseDouble(patrol_point.get(i).longitude), context));
                LatLng latLng2 = UIUtils.getGpsChangeLocation(Double.parseDouble(patrol_point.get(i).latitude), Double.parseDouble(patrol_point.get(i).longitude), context);
                Marker marker = mvRoute.getMap().addMarker(new MarkerOptions().position(latLng2).title("运维眼").snippet(""));
                marker.setObject(patrol_point.get(i).id);
            }
        }
        mvRoute.getMap().addPolyline(new PolylineOptions().
                addAll(latLngs).width(10).color(Color.argb(255, 239, 49, 49)));
        //画点
        mvRoute.getMap().setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker.isInfoWindowShown()) {
                    marker.hideInfoWindow();
                } else {
                    getPointInfo(marker);
                }
                return true;
            }
        });
    }

    private void getPointInfo(Marker marker) {
        ApiService.routePointInfoHttp((Integer) marker.getObject(), routeId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<PointInfoBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<List<PointInfoBean>> responseData) {
                        if (responseData.retCode == 10000) {
                            String str = "";
                            for (int i = 0; i < responseData.data.size(); i++) {
                                str = str + responseData.data.get(i).name + "\n"
                                        + responseData.data.get(i).manufacturer + "\n"
                                        + responseData.data.get(i).kks + "\n";
                            }
                            marker.setSnippet(str);
                            marker.showInfoWindow();
                        } else {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initMap(savedInstanceState);
    }

    private void initMap(Bundle savedInstanceState) {
        mvRoute.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mvRoute.onResume ()，重新绘制加载地图
        mvRoute.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mvRoute.onPause ()，暂停地图的绘制
        mvRoute.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mvRoute.onDestroy()，销毁地图
        mvRoute.onDestroy();
    }
}
